package cn.com.pajx.pajx_visitor_v3.api;

import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

import cn.com.pajx.pajx_visitor_v3.BaseApp;
import cn.com.pajx.pajx_visitor_v3.utils.CommonUtil;
import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by ruancw on 2018/5/22.
 * 网络请求类
 */

public class HttpApiService {
    private final Retrofit retrofit;

    public static HttpApiService getInstance() {
        return Singleton.instance;
    }

    private static class Singleton {
        private static final HttpApiService instance = new HttpApiService();
    }

    private HttpApiService() {
        retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())//解决上传图片带参数添加""的问题（必须放在Gson前）
                .addConverterFactory(GsonConverterFactory.create())//将返回的数据转为Gson
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加Rxjava的回调
                .client(genericClient())
                .build();
    }

    private OkHttpClient genericClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.MINUTES)
                .readTimeout(5, TimeUnit.MINUTES)
                .addInterceptor(chain -> {
                    Request request = chain.request();
                    request = request
                            .newBuilder()
                            .removeHeader("User-Agent")
                            .addHeader("User-Agent", CommonUtil.getUserAgent(BaseApp.getInstance()))
                            .build();
                    return chain.proceed(request);
                })
                .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    }

    private ApiService getApiService() {
        return getService(ApiService.class);
    }

    //通过retrofit获取ApiService实例
    private <T> T getService(Class<T> cls) {
        return retrofit.create(cls);
    }

    //获取网络数据
    public Observable getRemoteData(String url, LinkedHashMap<String, String> paramsMap, String aesKey) {
        String data = HttpParamsUtil.paramsToJson(paramsMap);
        return getApiService().getRemoteData(url, HttpParamsUtil.generateBodyJson(data, aesKey));
    }

    //上传文件
    public Observable updateFile(String url, MultipartBody.Part file, LinkedHashMap<String, String> map, String aesKey) {
        String data = HttpParamsUtil.paramsToJson(map);
        return getApiService().upLoadPhoto(url, file, HttpParamsUtil.generateBodyJson(data, aesKey));
    }

    //下载文件
    public Observable downloadFile(String url, LinkedHashMap<String, String> map) {
        return getApiService().downloadFile(url, map);
    }

}
